# coding=utf-8
from pyalgotrade import strategy
from pyalgotrade.bar import Frequency
from pyalgotrade.barfeed.csvfeed import GenericBarFeed
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.technical import rsi
from pyalgotrade import plotter
from pyalgotrade.stratanalyzer import returns, sharpe, drawdown, trades
import mongofeed
from Core.Config import *
import datetime
import pytz


###################################3
# ---Build Strategy---
class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed):
        super(MyStrategy, self).__init__(feed)
        self._instruments = feed._BarFeed__bars.keys()

        self._sma = {}
        for instrument in self._instruments:
            # --- Simple Moving Average ---
            self._sma[instrument] = ma.SMA(feed[instrument].getCloseDataSeries(), 2)

            # --- Relative Strength Index ---
            self._rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
            self._rsisma = ma.SMA(self._rsi, 15)

    def onBars(self, bars):  # 每一个数据都会抵达这里，就像becktest中的next
        for symbol in self._instruments:
            bar = bars[symbol]
            # Print Data
            self.info(symbol + " Close " + str(bar.getClose()))  # print Close
            self.info(symbol + " Average " + str(self._sma[symbol][-1])) # print SMA 2


        #if self._sma[-1] is None:
        #    return



#################################################
# --- Prepare and Load Data ------
# ---使用本地数据 CSV---
#feed = GenericBarFeed(Frequency.DAY, None, None)
#path = "D:/Data/PyAlgoTradeData/"
#feed.addBarsFromCSV("fd", path+"Test.csv")

# Load the yahoo feed from the CSV file
# path = "D:/Data/PyAlgoTradeData/Yahoo/"
#feed = yahoofeed.Feed()
#feed.addBarsFromCSV("000001.SZ", path+"000001.SZ.csv")

# ---使用数据库数据---
tz = pytz.timezone("Asia/Shanghai")
feed = mongofeed.Feed(timezone=tz)

# DateTiem Range
datetime1 = datetime.datetime(2018,1,1)
datetime2 = datetime.datetime(2018,7,1)

# ---Multi Instrument Load Data from Database---
feed.addBarsFromDataBase(database, "000001.SZ", "Quote/000001.SZ_Time_86400_Bar", datetime1, datetime2)
feed.addBarsFromDataBase(database, "000002.SZ", "Quote/000002.SZ_Time_86400_Bar", datetime1, datetime2)


#################################################
# ---Build Strategy, Prepare Statistics Index---
myStrategy = MyStrategy(feed)
plt = plotter.StrategyPlotter(myStrategy)
#
sharpe_ratio = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpe_ratio)


# ---Run the Strategy---
myStrategy.run()

# ---Statistics---
myStrategy.info("sharpe_ratio %.2f" % sharpe_ratio.getSharpeRatio(0))
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())
#plt.plot()#